package com.daxidi.cn.controller;

import com.daxidi.cn.params.DelFileParam;
import com.daxidi.cn.utils.ReturnResult;
import com.daxidi.cn.utils.ReturnResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "图片上传接口")
@Log4j
@RequestMapping("/api/v1/unions/file")
@RestController
public class FileController {

    @Value("${pic.upload.location}")
    private String fileLocation;

    @Value("${pic.upload.sysLocation}")
    private String sysLocation;

    @ApiOperation(value = "图片上传", notes = "上传图片")
    @ApiResponses({
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对"),
            @ApiResponse(code = 509, message = "上传图片不能为空"),
            @ApiResponse(code = 510, message = "文件已存在"),
            @ApiResponse(code = 508, message = "上传图片失败")
    })
    @PostMapping(value = "/picUpload")
    public ReturnResult picUpload(@RequestParam("uploadFile") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            ReturnResultUtils.returnFailMsg(509, "上传图片不能为空！");
        }
        //获取上传文件的名称
        String uploadFileName = multipartFile.getOriginalFilename();
        String strFile = uploadFileName.substring(0, uploadFileName.indexOf("."));
        String strFile2 = uploadFileName.substring(uploadFileName.indexOf("."));
        if (strFile.length() > 10) {
            strFile = strFile.substring(0, 10);
        }
        uploadFileName = strFile + System.currentTimeMillis() + strFile2;
        String path = fileLocation + uploadFileName;
        //创建文件路径
        File dest = new File(path);
        //判断文件是否已经存在
        if (dest.exists()) {
            return ReturnResultUtils.returnFailMsg(510, "文件已经存在");
        }
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            //上传文件
            multipartFile.transferTo(dest); //保存文件
            System.out.print("保存文件路径" + path + "\n");
        } catch (IOException e) {
            log.error("图片上传失败！" + e);
            e.printStackTrace();
            ReturnResultUtils.returnFailMsg(508, "上传头像失败");
        }
        String userPics = sysLocation + uploadFileName;
        Map<String, String> userPicMap = new HashMap<>();
        userPicMap.put("userPic", userPics);
        return ReturnResultUtils.returnSuccess(userPicMap);
    }


    @ApiOperation(value = "图片批量上传", notes = "上传图片")
    @ApiResponses({
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对"),
            @ApiResponse(code = 509, message = "上传图片不能为空"),
            @ApiResponse(code = 510, message = "文件已存在"),
            @ApiResponse(code = 508, message = "上传图片失败")
    })
    @PostMapping(value = "/picUploads")
    public ReturnResult picUploads(@RequestParam("uploadFile") MultipartFile[] file) {
        String msg = "";//返回存储路径
        HashMap<String, Object> map = new HashMap<>();
        if (file != null && file.length > 0) {
            for (int i = 0; i < file.length; i++) {
                String fileName = file[i].getOriginalFilename();//获取文件名加后缀
                //获取上传文件的名称
                String strFile = fileName.substring(0, fileName.indexOf("."));
                String strFile2 = fileName.substring(fileName.indexOf("."));
                if (strFile.length() > 10) {
                    strFile = strFile.substring(0, 10);
                }
                fileName = strFile + System.currentTimeMillis() + strFile2;
                if (fileName != null && fileName != "") {
                    String returnUrl = sysLocation;//文件访问路径
                    File file1 = new File(fileLocation + fileName);
                    //判断文件是否已经存在
                    if (file1.exists()) {
                        return ReturnResultUtils.returnFailMsg(510, "文件已经存在");
                    }
                    //判断文件父目录是否存在
                    if (!file1.getParentFile().exists()) {
                        file1.getParentFile().mkdir();
                    }
                    try {
                        file[i].transferTo(file1);
                        msg = returnUrl + fileName;
                        map.put(i + "", msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return ReturnResultUtils.returnSuccess(map);
    }

    @ApiOperation(value = "图片删除", notes = "删除图片")
    @ApiResponses({
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对"),
            @ApiResponse(code = 511, message = "删除图片失败")
    })
    @DeleteMapping(value = "/picDelete")
    public ReturnResult picDelete(@RequestBody DelFileParam delFileParam) {
        try {
            String pathFile = delFileParam.getPath().substring(sysLocation.length());
            deleteFile(fileLocation + pathFile);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("图片删除失败！" + e);
            return ReturnResultUtils.returnFailMsg(511, "删除图片失败");
        }
    }

    /**
     * 删除单个文件
     *
     * @param sPath 被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    private static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
}
